<template>
  <div class="product-detail-container">
    <!-- 添加商店信息展示到顶部 -->
    <div class="store-info" v-if="store">
      <div class="store-content">
        <router-link
          :to="{
            name: 'StoreDetail',
            params: { id: store?.id?.toString() ?? '' },
          }"
          class="store-link"
        >
          <img
            :src="store.imageUrl"
            :alt="store.name"
            class="store-logo"
            @error="handleImageError"
          />
          <div class="store-details">
            <div class="store-name">{{ store.name }}</div>
            <div class="store-stats">
              商品数: {{ product?.salesCount || 0 }}
            </div>
          </div>
        </router-link>
        <!-- 添加客服按钮 -->
        <a-button
          class="service-btn"
          type="primary"
          @click="handleCustomerService"
        >
          <message-outlined />
          联系客服
        </a-button>
      </div>
    </div>

    <div class="product-content">
      <!-- 左侧图片展示区 -->
      <div class="left-section">
        <div class="main-image">
          <img
            :src="getImageUrl(product?.imageUrl)"
            :alt="product?.name"
            @error="handleImageError"
          />
        </div>
      </div>

      <!-- 右侧商品信息区 -->
      <div class="right-section">
        <!-- 商品标题 -->
        <h1 class="product-name">{{ product?.name }}</h1>

        <!-- 商品描述 -->
        <div class="product-desc">{{ product?.description }}</div>

        <!-- 价格区域 -->
        <div class="price-section">
          <div class="current-price">
            <span class="label">券后</span>
            <span class="price-symbol">¥</span>
            <span class="price-value">{{ product?.price?.toFixed(2) }}</span>
            <span class="original-price"
              >优惠前¥{{ (product?.price || 0) + 228 }}</span
            >
          </div>
          <div class="sale-info">已售 {{ product?.salesCount || 57 }}</div>
        </div>

        <!-- 商品信息 -->
        <div class="product-attrs">
          <div class="attr-item">
            <span class="label">颜色</span>
            <span class="value">{{ product?.color }}</span>
          </div>
          <div class="attr-item">
            <span class="label">商品编号</span>
            <span class="value">{{ product?.id }}</span>
          </div>
        </div>

        <!-- 尺码选择 -->
        <div class="size-section">
          <div class="label">尺码</div>
          <div class="size-options">
            <div
              v-for="size in product?.sizeStocks"
              :key="size.id"
              class="size-item"
              :class="{
                selected: selectedSize === size.size,
                disabled: (size.stock ?? 0) <= 0,
              }"
              @click="handleSizeSelect(size)"
            >
              {{ size.size }}
              <span class="stock-tip" v-if="(size.stock ?? 0) > 0">
                剩余{{ size.stock }}件
              </span>
              <span class="stock-tip out-of-stock" v-else> 无货 </span>
            </div>
          </div>
        </div>

        <!-- 数量选择 -->
        <div class="quantity-section">
          <span class="label">数量</span>
          <a-input-number
            v-model:value="quantity"
            :min="1"
            :max="currentSizeStock"
            :disabled="!selectedSize"
          />
          <span class="stock-info" v-if="currentSizeStock > 0">
            库存{{ currentSizeStock }}件
          </span>
        </div>

        <!-- 按钮区域 -->
        <div class="action-buttons">
          <a-button
            type="primary"
            size="large"
            :disabled="!canBuy"
            @click="handleBuyNow"
          >
            立即购买
          </a-button>
          <a-button
            class="add-cart"
            size="large"
            :disabled="!canBuy"
            @click="handleAddToCart"
          >
            加入购物车
          </a-button>
        </div>
      </div>
    </div>

    <!-- 添加确认订单模态框 -->
    <a-modal
      v-model:visible="confirmOrderVisible"
      title="确认订单"
      width="800px"
      :footer="null"
    >
      <!-- 收货地址选择 -->
      <div class="address-section">
        <div class="section-title">
          <span>确认收货地址</span>
          <a-button type="link" @click="handleManageAddress"
            >管理收货地址</a-button
          >
        </div>
        <div class="address-list">
          <a-radio-group v-model:value="selectedAddressId">
            <div
              v-for="address in addressList"
              :key="address.id"
              class="address-item"
              :class="{ selected: selectedAddressId === address.id }"
            >
              <a-radio :value="address.id">
                <div class="address-content">
                  <div class="address-header">
                    <span class="consignee">{{ address.consignee }}</span>
                    <span class="phone">{{ formatPhone(address.phone) }}</span>
                    <a-tag v-if="address.label" color="blue">
                      {{ address.label }}
                    </a-tag>
                    <a-tag v-if="address.isDefault" color="red">默认</a-tag>
                  </div>
                  <div class="address-detail">
                    {{ formatAddress(address) }}
                  </div>
                </div>
              </a-radio>
            </div>
          </a-radio-group>
        </div>
      </div>

      <!-- 订单信息 -->
      <div class="order-section">
        <div class="section-title">确认订单信息</div>
        <div class="product-info">
          <div class="product-detail">
            <div class="product-name">{{ product?.name }}</div>
            <div class="product-attrs">
              <span class="attr-item">颜色：{{ product?.color }}</span>
              <span class="attr-item">尺码：{{ selectedSize }}</span>
            </div>
            <div class="product-price">¥{{ product?.price?.toFixed(2) }}</div>
          </div>
          <div class="quantity-info">
            <span>x{{ quantity }}</span>
          </div>
        </div>
        <div class="delivery-info">
          <span class="label">配送方式</span>
          <span class="value">快递 免邮</span>
        </div>
        <div class="message-info">
          <span class="label">买家留言</span>
          <a-input
            v-model:value="buyerMessage"
            placeholder="选填：建议留言前先与商家沟通确认"
            :maxLength="200"
          />
        </div>
      </div>

      <!-- 提交订单 -->
      <div class="submit-section">
        <div class="submit-content">
          <div class="price-info">
            <span>实付款：</span>
            <span class="total-price">¥{{ totalPrice }}</span>
          </div>
          <div class="address-info" v-if="selectedAddress">
            <span>寄送至：{{ formatAddress(selectedAddress) }}</span>
            <span class="divider">|</span>
            <span>
              收货人：{{ selectedAddress.consignee }}
              {{ formatPhone(selectedAddress.phone) }}
            </span>
          </div>
          <a-button
            type="primary"
            size="large"
            :disabled="!canSubmit"
            :loading="submitting"
            @click="handleSubmitOrder"
          >
            提交订单
          </a-button>
        </div>
      </div>
    </a-modal>

    <!-- 添加导航栏和内容区域 -->
    <div class="detail-container">
      <div class="detail-nav">
        <div
          class="nav-item"
          :class="{ active: activeTab === 'params' }"
          @click="activeTab = 'params'"
        >
          产品参数
        </div>
        <div
          class="nav-item"
          :class="{ active: activeTab === 'details' }"
          @click="activeTab = 'details'"
        >
          图文详情
        </div>
        <div
          class="nav-item"
          :class="{ active: activeTab === 'comments' }"
          @click="activeTab = 'comments'"
        >
          商品评论
        </div>
      </div>

      <!-- 产品参数表格 -->
      <div v-if="activeTab === 'params'" class="params-table">
        <div class="detail-title">产品参数详情</div>
        <table>
          <tbody>
            <tr v-for="(chunk, index) in paramChunks" :key="index">
              <template v-for="(item, key) in chunk" :key="key">
                <td class="param-key">{{ key }}</td>
                <td class="param-value">{{ item }}</td>
              </template>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 修改图文详情部分 -->
      <div v-else-if="activeTab === 'details'" class="product-details">
        <div class="detail-title">商品详情</div>
        <div v-if="detailImages.length === 0" class="empty-details">
          暂无详情图片
        </div>
        <div class="detail-images-list">
          <div
            v-for="image in detailImages"
            :key="image.id"
            class="detail-image-wrapper"
          >
            <img
              :src="getDetailImageUrl(image.imageName)"
              :alt="product?.name"
              @error="handleImageError"
              class="detail-image"
            />
          </div>
        </div>
      </div>

      <!-- 添加评论区域 -->
      <div v-else-if="activeTab === 'comments'" class="comments-section">
        <!-- 评分统计 -->
        <div class="rating-summary">
          <div class="average-rating">
            <span class="rating-number">{{ averageRating }}</span>
            <a-rate :value="averageRating" disabled allow-half />
          </div>
          <div class="rating-count">共 {{ totalComments }} 条评论</div>
        </div>

        <!-- 评论列表 -->
        <div class="comments-list">
          <!-- 前三条评论 -->
          <div
            v-for="comment in displayComments"
            :key="comment.id"
            class="comment-item"
          >
            <div class="comment-header">
              <a-avatar :src="comment.userAvatar || defaultAvatar" />
              <div class="comment-info">
                <div class="username">{{ comment.userName }}</div>
                <div class="rating">
                  <a-rate :value="comment.rating" disabled />
                  <span class="comment-time">{{
                    formatDate(comment.createdAt)
                  }}</span>
                </div>
              </div>
            </div>
            <div class="comment-content">{{ comment.content }}</div>
            <div
              v-if="comment.imageList && comment.imageList.length"
              class="comment-images"
            >
              <a-image-preview-group>
                <a-image
                  v-for="(img, index) in comment.imageList"
                  :key="index"
                  :src="img"
                  :width="100"
                />
              </a-image-preview-group>
            </div>
          </div>

          <!-- 加载更多按钮 -->
          <div v-if="totalComments === 0" class="empty-comments">暂无评论</div>
          <div class="load-more" v-else-if="totalComments > 3">
            <a-button
              v-if="!showAllComments"
              @click="handleShowMore"
              :loading="loadingMore"
            >
              查看更多评论
            </a-button>
            <a-pagination
              v-else
              v-model:current="currentPage"
              :total="totalComments"
              :pageSize="pageSize"
              @change="handlePageChange"
              show-less-items
            />
          </div>
        </div>

        <!-- 发表评论 -->
        <div v-if="canComment" class="comment-form">
          <h3>发表评论</h3>
          <a-form :model="commentForm" @finish="handleSubmitComment">
            <a-form-item label="评分">
              <a-rate v-model:value="commentForm.rating" />
            </a-form-item>
            <a-form-item label="评论内容">
              <a-textarea
                v-model:value="commentForm.content"
                :rows="4"
                placeholder="请输入您的评价"
              />
            </a-form-item>
            <a-form-item label="上传图片">
              <a-upload
                v-model:fileList="fileList"
                list-type="picture-card"
                :before-upload="beforeUpload"
                @preview="handlePreview"
                @remove="handleRemove"
              >
                <div v-if="fileList.length < 6">
                  <plus-outlined />
                  <div style="margin-top: 8px">上传</div>
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" html-type="submit" :loading="submitting">
                提交评论
              </a-button>
            </a-form-item>
          </a-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { message } from "ant-design-vue";
import {
  StarOutlined,
  PlusOutlined,
  MessageOutlined,
} from "@ant-design/icons-vue";

const defaultAvatar = "https://joeschmoe.io/api/v1/random";
import { getProductUsingGet } from "@/api/shangpinjiekou";
import { listUsingGet } from "@/api/addressBookController";
import { createOrderUsingPost } from "@/api/orderController";
import { addToCartUsingPost } from "@/api/shoppingCartController";
import { getParamsUsingPost } from "@/api/productParamController";
import { getProductImagesUsingPost } from "@/api/productImageController";
import { uploadFileUsingPost } from "@/api/cosController";
import {
  addCommentUsingPost1,
  getProductCommentsUsingGet,
  getAverageRatingUsingGet,
  getCommentCountUsingGet1,
} from "@/api/productCommentController";
import type API from "@/api";
import { getStoreInfoUsingPost } from "@/api/storeController";

const route = useRoute();
const router = useRouter();
const product = ref<API.ClothingProduct>();
const selectedSize = ref<string | undefined>(undefined);
const quantity = ref<number>(1);

// 添加商店信息的状态
const store = ref<API.Store>();

// 修改详情图片URL获取方法
const getDetailImageUrl = (imageUrl: string | undefined) => {
  if (!imageUrl) {
    return "https://img.js.design/assets/img/64832e1d1b5cdf515c927925.png#2aa0fdda"; // 使用远程默认图片
  }

  // 如果是完整的URL，直接返回
  if (imageUrl.startsWith("http")) {
    return imageUrl;
  }

  // 如果不是完整URL，使用默认图片
  return "https://img.js.design/assets/img/64832e1d1b5cdf515c927925.png#2aa0fdda";
};

// 同样修改主图片的URL获取方法
const getImageUrl = (imageUrl: string | undefined) => {
  if (!imageUrl) {
    return "https://img.js.design/assets/img/64832e1d1b5cdf515c927925.png#2aa0fdda";
  }

  // 如果是完整的URL，直接返回
  if (imageUrl.startsWith("http")) {
    return imageUrl;
  }

  // 如果不是完整URL，使用默认图片
  return "https://img.js.design/assets/img/64832e1d1b5cdf515c927925.png#2aa0fdda";
};

// 修改图片加载失败处理函数
const handleImageError = (e: Event) => {
  const img = e.target as HTMLImageElement;
  img.src =
    "https://img.js.design/assets/img/64832e1d1b5cdf515c927925.png#2aa0fdda";
};

// 详情图片列表
const detailImages = ref<API.ProductImage[]>([]);

// 加载详情图片
const loadDetailImages = async () => {
  try {
    const productId = Number(route.params.id);
    if (!productId) return;

    const res = await getProductImagesUsingPost({ productId });
    if (res.data?.code === 0 && res.data.data) {
      detailImages.value = res.data.data;
      console.log(detailImages.value);
    }
  } catch (error) {
    console.error("获取商品详情图片失败:", error);
  }
};

// 获取当前选中尺码的库存
const currentSizeStock = computed(() => {
  if (!selectedSize.value || !product.value?.sizeStocks) return 0;
  const sizeStock = product.value.sizeStocks.find(
    (item) => item.size === selectedSize.value
  );
  return sizeStock?.stock || 0;
});

// 是否可以购买
const canBuy = computed(() => {
  return (
    selectedSize.value &&
    quantity.value > 0 &&
    quantity.value <= currentSizeStock.value
  );
});

// 选择尺码
const handleSizeSelect = (size: API.SizeStock) => {
  if (!size.stock || size.stock <= 0) return;
  selectedSize.value = size.size || undefined;
  if (quantity.value > (size.stock || 0)) {
    quantity.value = size.stock;
  }
};

// 加载商品详情
const loadProductDetail = async () => {
  try {
    const productId = Number(route.params.id);
    if (!productId) {
      message.error("商品ID无效");
      return;
    }

    const res = await getProductUsingGet({ id: productId });
    if (res.data?.code === 0 && res.data.data) {
      product.value = res.data.data;
      // 加载商店信息
      await loadStoreInfo();
    }
  } catch (error) {
    message.error("获取商品详情失败");
  }
};

// 添加加载商店信息的方法
const loadStoreInfo = async () => {
  try {
    if (!product.value?.storeId) return;

    const res = await getStoreInfoUsingPost({ storeId: product.value.storeId });
    if (res.data?.code === 0 && res.data.data) {
      store.value = res.data.data;
    }
  } catch (error) {
    console.error("获取商店信息失败:", error);
    message.error("获取商店信息失败");
  }
};

// 订单相关
const confirmOrderVisible = ref(false);
const addressList = ref<API.AddressBook[]>([]);
const selectedAddressId = ref<number | undefined>(undefined);
const buyerMessage = ref("");
const submitting = ref(false);

// 计算总价
const totalPrice = computed(() => {
  return ((product.value?.price || 0) * quantity.value).toFixed(2);
});

// 获取选中的地址
const selectedAddress = computed(() => {
  return addressList.value.find((addr) => addr.id === selectedAddressId.value);
});

// 是否可以提交订单
const canSubmit = computed(() => {
  return selectedAddressId.value && selectedSize.value && quantity.value > 0;
});

// 格式化手机号
const formatPhone = (phone?: string) => {
  if (!phone) return "";
  return `${phone.slice(0, 3)}****${phone.slice(7)}`;
};

// 格式化地址
const formatAddress = (address: API.AddressBook) => {
  return `${address.provinceName}${address.cityName}${address.districtName}${address.detail}`;
};

// 加载地址列表
const loadAddressList = async () => {
  try {
    const res = await listUsingGet();
    if (res.data?.code === 0 && res.data.data) {
      addressList.value = res.data.data;
      // 默认选中默认地址
      const defaultAddress = res.data.data.find((addr) => addr.isDefault === 1);
      if (defaultAddress?.id) {
        selectedAddressId.value = defaultAddress.id;
      }
    }
  } catch (error) {
    message.error("获取地址列表失败");
  }
};

// 修改立即购买函数
const handleBuyNow = () => {
  if (!canBuy.value) {
    message.warning("请选择尺码和数量");
    return;
  }

  router.push({
    path: "/order/create",
    query: {
      productId: product.value?.id,
      size: selectedSize.value,
      quantity: quantity.value,
    },
  });
};

// 提交订单
const handleSubmitOrder = async () => {
  if (!canSubmit.value || !selectedAddressId.value) return;

  try {
    submitting.value = true;
    // 使用类型断言解决类型问题
    const orderData = {
      addressId: selectedAddressId.value,
      productId: product.value?.id,
      size: selectedSize.value || "",
      quantity: quantity.value,
      message: buyerMessage.value,
    } as API.OrderCreateRequest;

    const res = await createOrderUsingPost(orderData);
    if (res.data?.code === 0 && res.data.data) {
      message.success("下单成功");
      confirmOrderVisible.value = false;
      router.push(`/order/${res.data.data.id}`);
    }
  } catch (error) {
    message.error("创建订单失败");
  } finally {
    submitting.value = false;
  }
};

// 管理收货地址
const handleManageAddress = () => {
  router.push("/user/address");
};

// 加入购物车
const handleAddToCart = async () => {
  if (!canBuy.value) {
    message.warning("请先选择尺码和数量");
    return;
  }

  try {
    // 使用类型断言解决类型问题
    const cartItem = {
      productId: product.value?.id,
      productImage: product.value?.imageUrl,
      price: product.value?.price,
      size: selectedSize.value,
      quantity: quantity.value,
      selected: 0,
    } as API.ShoppingCartItem;

    const res = await addToCartUsingPost(cartItem);
    if (res.data?.code === 0) {
      message.success("添加到购物车成功");
    } else {
      message.error(res.data?.message || "添加到购物车失败");
    }
  } catch (error) {
    console.error("添加到购物车失败:", error);
    message.error("添加到购物车失败，请稍后重试");
  }
};

// 添加标签页状态
const activeTab = ref("params");
const productParams = ref<Record<string, any>>({});

// 加载产品参数
const loadProductParams = async () => {
  try {
    const productId = Number(route.params.id);
    if (!productId) return;

    const res = await getParamsUsingPost({ productId });
    if (res.data?.code === 0 && res.data.data?.params) {
      productParams.value = res.data.data.params;
    }
  } catch (error) {
    console.error("获取商品参数失败:", error);
  }
};

// 将参数分组为每组两个
const paramChunks = computed(() => {
  const params = productParams.value;
  const result = [];
  const keys = Object.keys(params);

  for (let i = 0; i < keys.length; i += 2) {
    const chunk: Record<string, any> = {};
    chunk[keys[i]] = params[keys[i]];
    if (i + 1 < keys.length) {
      chunk[keys[i + 1]] = params[keys[i + 1]];
    }
    result.push(chunk);
  }

  return result;
});

const comments = ref<API.ProductComment[]>([]);
const averageRating = ref(0);
const totalComments = ref(0);
const fileList = ref<any[]>([]);

const commentForm = ref({
  rating: 5,
  content: "",
});

// 检查用户是否可以评论（例如：已购买且未评论）
const canComment = ref(true); // 这里需要根据实际业务逻辑判断

// 分页相关的状态
const showAllComments = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const loadingMore = ref(false);
const allComments = ref<API.ProductComment[]>([]);

// 计算当前显示的评论
const displayComments = computed(() => {
  if (!showAllComments.value) {
    return allComments.value.slice(0, 3);
  }
  return allComments.value;
});

// 格式化日期
const formatDate = (date?: string) => {
  if (!date) return "";
  return new Date(date).toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "long",
    day: "numeric",
  });
};

// 修改加载评论数据的方法
const loadComments = async (page = 1, loadAll = false) => {
  try {
    const productId = Number(route.params.id);
    if (!productId) return;

    loadingMore.value = true;
    const [commentsRes, ratingRes, countRes] = await Promise.all([
      getProductCommentsUsingGet({
        productId,
        pageNum: page,
        pageSize: loadAll ? pageSize.value : 3,
      }),
      getAverageRatingUsingGet({ productId }),
      getCommentCountUsingGet1({ productId }),
    ]);

    if (commentsRes.data?.code === 0 && commentsRes.data.data) {
      // 处理评论数据，确保imageList字段正确
      const processedComments = (commentsRes.data.data.records || []).map(
        (comment: any) => {
          // 如果imageList存在，直接使用，否则尝试解析images字段
          if (!comment.imageList && comment.images) {
            try {
              // 尝试解析JSON字符串
              comment.imageList = JSON.parse(comment.images);
            } catch (e) {
              // 如果解析失败，尝试直接分割字符串
              comment.imageList = comment.images.split(",").filter(Boolean);
            }
          }
          return comment;
        }
      );

      if (page === 1) {
        allComments.value = processedComments;
      } else {
        // 追加新评论
        allComments.value = allComments.value.concat(processedComments);
      }

      console.log("评论数据:", allComments.value); // 添加日志确认数据
    }

    if (ratingRes.data?.code === 0) {
      averageRating.value = ratingRes.data.data || 0;
    }
    if (countRes.data?.code === 0) {
      totalComments.value = countRes.data.data || 0;
    }
  } catch (error) {
    console.error("加载评论失败:", error);
    message.error("加载评论失败");
  } finally {
    loadingMore.value = false;
  }
};

// 处理查看更多评论
const handleShowMore = async () => {
  showAllComments.value = true;
  currentPage.value = 1;
  await loadComments(1, true);
};

// 处理分页变化
const handlePageChange = async (page: number) => {
  currentPage.value = page;
  await loadComments(page, true);
  // 滚动到评论区域顶部
  const commentsSection = document.querySelector(".comments-section");
  commentsSection?.scrollIntoView({ behavior: "smooth" });
};

// 修改评论提交后的处理
const handleSubmitComment = async () => {
  if (!commentForm.value.content.trim()) {
    message.warning("请输入评论内容");
    return;
  }

  try {
    submitting.value = true;

    // 1. 先上传图片
    const uploadedImages = await Promise.all(
      fileList.value.map(async (file) => {
        const formData = new FormData();
        formData.append("file", file.originFileObj);
        const res = await uploadFileUsingPost({}, file.originFileObj);
        if (res.data?.code === 0 && res.data.data) {
          return res.data.data; // 返回图片URL
        }
        throw new Error("上传图片失败");
      })
    );

    // 2. 提交评论
    const commentData: API.ProductComment = {
      productId: Number(route.params.id),
      content: commentForm.value.content,
      rating: commentForm.value.rating,
      images: uploadedImages.join(","), // 将图片URL数组转换为字符串
    };

    const res = await addCommentUsingPost1(commentData);
    if (res.data?.code === 0) {
      message.success("评论成功");
      // 重置表单
      commentForm.value.content = "";
      commentForm.value.rating = 5;
      fileList.value = [];
      // 重新加载评论
      currentPage.value = 1;
      showAllComments.value = false;
      await loadComments(1, false);
    } else {
      message.error(res.data?.message || "评论失败");
    }
  } catch (error) {
    console.error("提交评论失败:", error);
    message.error("提交评论失败");
  } finally {
    submitting.value = false;
  }
};

// 添加上传图片相关的方法
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith("image/");
  if (!isImage) {
    message.error("只能上传图片文件！");
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("图片必须小于 2MB！");
    return false;
  }
  return true;
};

const handlePreview = async (file: any) => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
};

const handleRemove = (file: any) => {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
};

// 辅助函数：将文件转换为 base64
function getBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });
}

// 跳转到店铺详情
const goToStore = (storeId: number) => {
  router.push({
    name: "StoreDetail",
    params: { id: storeId.toString() },
  });
};

// 修改客服处理函数
const handleCustomerService = () => {
  if (!store.value?.id) return;
  router.push({
    name: "CustomerService",
    params: {
      storeId: store.value.id.toString(),
      productId: product.value?.id?.toString(),
    },
    query: {
      from: "contact",
    },
  });
};

onMounted(() => {
  loadProductDetail();
  loadProductParams();
  loadDetailImages();
  loadComments();
});
</script>

<style scoped>
.product-detail-container {
  min-height: 100vh;
  background: url("@/assets/background/homeviewbackground.png") no-repeat center
    top;
  background-size: cover;
  padding: 40px 20px;
  position: relative;
}

.product-detail-container::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.1);
  z-index: 1;
}

.store-info {
  max-width: 1080px;
  margin: 0 auto 20px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  padding: 15px 20px;
  position: relative;
  z-index: 2;
  border: 1px solid rgba(165, 104, 60, 0.3);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: scale(0.9);
  transform-origin: top center;
}

.store-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
}

.store-link {
  display: flex;
  align-items: center;
  text-decoration: none;
  color: inherit;
}

.store-logo {
  width: 48px;
  height: 48px;
  object-fit: cover;
  border-radius: 50%;
  margin-right: 12px;
  border: 2px solid rgba(165, 104, 60, 0.3);
}

.store-details {
  flex: 1;
}

.store-name {
  font-size: 16px;
  font-weight: bold;
  color: #8c4b3c;
  margin-bottom: 4px;
}

.store-stats {
  font-size: 12px;
  color: #999;
}

.service-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  height: 36px;
  padding: 0 16px;
  border-radius: 18px;
  background: #8c4b3c;
  border: none;
  transition: all 0.3s ease;
}

.service-btn:hover {
  background: #a5683c;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(140, 75, 60, 0.3);
}

.product-content {
  max-width: 1080px;
  margin: 0 auto;
  display: flex;
  gap: 40px;
  background: rgba(255, 255, 255, 0.95);
  padding: 30px;
  border-radius: 8px;
  position: relative;
  z-index: 2;
  border: 1px solid rgba(165, 104, 60, 0.3);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: scale(0.9);
  transform-origin: top center;
}

.left-section {
  width: 400px;
  flex-shrink: 0;
}

.main-image {
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
}

.main-image img {
  width: 100%;
  height: auto;
  display: block;
}

.right-section {
  flex: 1;
  padding: 0 20px;
}

.vip-banner {
  background: #fff8e7;
  padding: 12px 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  font-size: 14px;
  color: #8c4b3c;
  display: flex;
  align-items: center;
  gap: 8px;
  border: 1px dashed rgba(165, 104, 60, 0.3);
}

.vip-tag {
  background: #8c4b3c;
  color: #fff;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.open-vip {
  margin-left: auto;
  color: #8c4b3c;
  text-decoration: none;
  font-weight: 500;
}

.open-vip:hover {
  color: #a5683c;
  text-decoration: underline;
}

.product-name {
  font-size: 24px;
  color: #333;
  margin: 0 0 20px;
  line-height: 1.4;
  font-family: "KaiTi", "楷体", serif;
}

.product-desc {
  color: #666;
  margin-bottom: 20px;
}

.price-section {
  background: rgba(140, 75, 60, 0.1);
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.current-price {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.label {
  font-size: 14px;
  color: #8c4b3c;
}

.price-symbol {
  color: #8c4b3c;
  font-size: 16px;
}

.price-value {
  color: #8c4b3c;
  font-size: 28px;
  font-weight: bold;
}

.original-price {
  color: #999;
  text-decoration: line-through;
  margin-left: 10px;
}

.sale-info {
  color: #999;
  font-size: 12px;
  margin-top: 8px;
}

.product-attrs {
  margin: 20px 0;
  padding: 15px 0;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
}

.attr-item {
  display: flex;
  margin-bottom: 10px;
}

.attr-item .label {
  color: #999;
  width: 80px;
}

.attr-item .value {
  color: #333;
}

.size-section {
  margin: 20px 0;
}

.size-options {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 10px;
}

.size-item {
  position: relative;
  padding: 8px 20px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.size-item:hover:not(.disabled) {
  border-color: #8c4b3c;
  color: #8c4b3c;
}

.size-item.selected {
  border-color: #8c4b3c;
  color: #8c4b3c;
  background: rgba(165, 104, 60, 0.05);
}

.size-item.disabled {
  color: #999;
  border-color: #eee;
  cursor: not-allowed;
  background: #f5f5f5;
}

.stock-tip {
  position: absolute;
  top: -20px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.7);
  color: #fff;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  opacity: 0;
  transition: opacity 0.3s;
}

.size-item:hover .stock-tip {
  opacity: 1;
}

.out-of-stock {
  color: #ff4d4f;
}

.quantity-section {
  margin: 20px 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.stock-info {
  color: #999;
  font-size: 14px;
}

.action-buttons {
  margin-top: 30px;
  display: flex;
  gap: 16px;
}

.action-buttons .ant-btn {
  height: 48px;
  font-size: 16px;
  padding: 0 40px;
}

.ant-btn-primary {
  background: #8c4b3c;
  border-color: #8c4b3c;
  color: #ffffff;
}

.ant-btn-primary:hover {
  background: #a5683c;
  border-color: #a5683c;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(140, 75, 60, 0.3);
  color: #ffffff;
}

.add-cart {
  border-color: #8c4b3c;
  color: #8c4b3c;
}

.add-cart:hover {
  color: #fff;
  background: #a5683c;
  border-color: #a5683c;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(140, 75, 60, 0.3);
}

.collect {
  width: 100px;
  height: 40px;
}

/* 响应式调整 */
@media screen and (max-width: 992px) {
  .product-content {
    flex-direction: column;
  }

  .left-section {
    width: 100%;
  }
}

@media screen and (max-width: 576px) {
  .action-buttons {
    flex-direction: column;
  }

  .buy-now,
  .add-cart,
  .collect {
    width: 100%;
  }
}

/* 确认订单模态框样式 */
.address-section,
.order-section {
  background: #fff;
  margin-bottom: 20px;
  border-radius: 4px;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.address-list {
  padding: 20px;
  max-height: 300px;
  overflow-y: auto;
}

.address-item {
  padding: 15px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  margin-bottom: 10px;
  transition: all 0.3s;
}

.address-item.selected {
  border-color: #ff4000;
}

.product-info {
  display: flex;
  padding: 15px;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 15px;
}

.product-detail {
  flex: 1;
}

.delivery-info,
.message-info {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.submit-section {
  background: #f8f8f8;
  padding: 20px;
  border-radius: 0 0 4px 4px;
}

.submit-content {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 20px;
}

.total-price {
  color: #ff4000;
  font-size: 20px;
  font-weight: bold;
}

:deep(.ant-modal-body) {
  padding: 0;
}

:deep(.ant-modal-header) {
  margin-bottom: 0;
}

/* 添加新样式 */
.detail-container {
  max-width: 1080px;
  margin: 40px auto;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  padding: 30px;
  position: relative;
  z-index: 2;
  border: 1px solid rgba(165, 104, 60, 0.3);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: scale(0.9);
  transform-origin: top center;
}

.detail-nav {
  display: flex;
  border-bottom: 1px solid rgba(165, 104, 60, 0.2);
  margin-bottom: 30px;
}

.nav-item {
  padding: 15px 30px;
  font-size: 16px;
  cursor: pointer;
  position: relative;
  color: #666;
  transition: all 0.3s;
  font-family: "KaiTi", "楷体", serif;
}

.nav-item:hover {
  color: #a5683c;
}

.nav-item.active {
  color: #8c4b3c;
  font-weight: 500;
}

.nav-item.active::after {
  content: "";
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background: #8c4b3c;
}

.detail-title {
  font-size: 20px;
  color: #8c4b3c;
  font-weight: bold;
  margin-bottom: 30px;
  text-align: center;
  position: relative;
  font-family: "KaiTi", "楷体", serif;
}

.detail-title::before,
.detail-title::after {
  content: "";
  position: absolute;
  top: 50%;
  width: 80px;
  height: 1px;
  background: rgba(165, 104, 60, 0.3);
}

.detail-title::before {
  left: calc(50% - 140px);
}

.detail-title::after {
  right: calc(50% - 140px);
}

.detail-image {
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid rgba(165, 104, 60, 0.2);
}

.rating-summary {
  background: rgba(165, 104, 60, 0.05);
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.average-rating {
  display: flex;
  align-items: center;
  gap: 10px;
}

.rating-number {
  font-size: 28px;
  font-weight: bold;
  color: #8c4b3c;
}

.rating-count {
  color: #666;
}

.comments-list {
  margin-bottom: 30px;
}

.empty-comments {
  text-align: center;
  padding: 30px;
  color: #999;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 8px;
  border: 1px dashed #ddd;
  margin: 20px 0;
}

.comment-item {
  background: rgba(255, 255, 255, 0.7);
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid rgba(165, 104, 60, 0.1);
  transition: all 0.3s;
}

.comment-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.08);
}

.comment-header {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
}

.comment-info {
  flex: 1;
}

.username {
  font-weight: 500;
  margin-bottom: 4px;
}

.comment-time {
  color: #999;
  margin-left: 10px;
  font-size: 12px;
}

.comment-content {
  margin: 12px 0;
  color: #333;
  word-break: break-word;
}

.comment-images {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-top: 12px;
}

.load-more {
  text-align: center;
  margin-top: 20px;
}

.comment-form {
  background: rgba(255, 255, 255, 0.7);
  border-radius: 8px;
  padding: 30px;
  margin-top: 40px;
  border: 1px solid rgba(165, 104, 60, 0.2);
}

.comment-form h3 {
  color: #8c4b3c;
  font-family: "KaiTi", "楷体", serif;
  text-align: center;
  margin-bottom: 20px;
  font-size: 20px;
  position: relative;
}

.comment-form h3::before,
.comment-form h3::after {
  content: "✦";
  color: rgba(165, 104, 60, 0.5);
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

.comment-form h3::before {
  left: calc(50% - 100px);
}

.comment-form h3::after {
  right: calc(50% - 100px);
}

/* 参数表格样式 */
.params-table {
  padding: 20px;
  width: 100%;
}

.params-table table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid rgba(165, 104, 60, 0.2);
}

.params-table tr {
  transition: all 0.3s;
}

.params-table tr:nth-child(odd) {
  background: rgba(165, 104, 60, 0.05);
}

.params-table tr:hover {
  background: rgba(165, 104, 60, 0.1);
}

.param-key {
  width: 120px;
  padding: 12px 20px;
  color: #8c4b3c;
  font-weight: 500;
  text-align: right;
  border-right: 1px solid rgba(165, 104, 60, 0.2);
  font-family: "KaiTi", "楷体", serif;
}

.param-value {
  width: calc(50% - 120px);
  padding: 12px 20px;
  color: #333;
  border-right: 1px solid rgba(165, 104, 60, 0.1);
}

.param-value:last-child {
  border-right: none;
}
</style>
